#include "UsbEnumerator.h"
#include <malloc.h>
#include <tchar.h>


UsbEnumerator::UsbEnumerator(const WCHAR* infFile)
{
	MapFile(infFile);
}
void UsbEnumerator::MapFile(const WCHAR* filename)
{
	wifstream infile(filename);	
	wstringstream tmpStream;
	WCHAR tmpLine[200];
	int c;
	wstring tmp;

	if(infile.fail())
		return;

	while (!infile.eof() && !infile.fail())
	{
		c = infile.get();
		if(c == '\t')
		{
			infile >> tmp;
			infile.getline(tmpLine, 200);

			tmpStream << tmpLine;
			PID_MAP[tmp] = tmpStream.str();	
			tmpStream.str(L"");
			continue;
		}
		infile.unget();
		infile >> tmp;		
		infile.getline(tmpLine, 200);

		tmpStream << tmpLine;
		VID_MAP[tmp] = tmpStream.str();	
		tmpStream.str(L"");
	}	
}

void UsbEnumerator::ToEnumerate()
{
	HDEVINFO                         deviceInfo;
	SP_DEVICE_INTERFACE_DATA         deviceInfoData;
	PSP_DEVICE_INTERFACE_DETAIL_DATA deviceDetailData;
	ULONG                            index;
	ULONG							requiredLength;
	
	
	deviceInfo = SetupDiGetClassDevs((LPGUID)&GUID_DEVINTERFACE_USB_DEVICE,
					NULL,
					NULL,
					(DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));

	if (deviceInfo != INVALID_HANDLE_VALUE)
	{
		deviceInfoData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

		for (index=0; SetupDiEnumDeviceInterfaces(deviceInfo,
						0,
						(LPGUID)&GUID_DEVINTERFACE_USB_DEVICE,
						index,
						&deviceInfoData);
			index++)
		{
			SetupDiGetDeviceInterfaceDetail(deviceInfo,
											&deviceInfoData,
											NULL,
											0,
											&requiredLength,
											NULL);

			deviceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)GlobalAlloc(GPTR, requiredLength);

			deviceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

			SetupDiGetDeviceInterfaceDetail(deviceInfo,
				&deviceInfoData,
				deviceDetailData,
				requiredLength,
				&requiredLength,
				NULL);

			
			deviceList.append(new DeviceInformation(deviceDetailData->DevicePath, NULL, NULL));//&VID_MAP, &PID_MAP));
		}
	}
}